<script setup lang="ts">
import type { SettlementInfo } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getSysSettlementDetails } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '账单结算详情',
    enablePullDownRefresh: true,
  },
})

// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<SettlementInfo>(null)
const errorMessage = ref('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')
// 获取冻结状态文本
function getFreezeStatusText(status?: number): string {
  const statusMap: Record<number, string> = {
    0: '未冻结',
    1: '已冻结',
  }
  return status !== undefined ? statusMap[status] || '--' : '--'
}

// 获取开票状态文本
function getInvoiceStatusText(status?: number): string {
  const statusMap: Record<number, string> = {
    0: '未开票',
    1: '已开票',
  }
  return status !== undefined ? statusMap[status] || '--' : '--'
}

// 获取退款状态文本
function getRefundStatusText(status?: number): string {
  const statusMap: Record<number, string> = {
    0: '否',
    1: '是',
  }
  return status !== undefined ? statusMap[status] || '--' : '--'
}

// 获取资金类型文本
function getFundsTypeText(type?: number): string {
  const typeMap: Record<number, string> = {
    1: '收入',
    2: '支出',
  }
  return type !== undefined ? typeMap[type] || '--' : '--'
}

// 获取结算类型文本
function getSettlementTypeText(type?: number): string {
  const typeMap: Record<number, string> = {
    1: '应收',
    2: '应付',
  }
  return type !== undefined ? typeMap[type] || '--' : '--'
}

// 计算基本信息列表
const basicInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '结算编号',
      value: businessData.value.settlementNo || '--',
    },
    {
      label: '资金类型',
      value: getFundsTypeText(businessData.value.fundsType),
    },
    {
      label: '结算类型',
      value: getSettlementTypeText(businessData.value.settlementType),
    },
    {
      label: '应付金额',
      value: businessData.value.payment || 0,
      type: 'currency',
    },
    {
      label: '实际支付金额',
      value: businessData.value.actualPayment || 0,
      type: 'currency',
    },
    {
      label: '审批状态',
      value: businessData.value.approvalStatus,
      type: 'approval',
    },
    {
      label: '冻结状态',
      value: getFreezeStatusText(businessData.value.freezeStatus),
    },
    {
      label: '是否退款',
      value: getRefundStatusText(businessData.value.isRefund),
    },
  ]
})

// 计算业务信息列表
const businessInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '业务机构',
      value: businessData.value.businessInstitutionName || '--',
    },
    {
      label: '业务部门',
      value: businessData.value.businessDepartmentName || '--',
    },
    {
      label: '业务员',
      value: businessData.value.salesmanName || '--',
    },
    {
      label: '运输类型',
      value: businessData.value.freightType_dictText || '--',
    },
    {
      label: '支付方式',
      value: businessData.value.paymentMethod_dictText || '--',
    },
    {
      label: '结算业务类型',
      value: businessData.value.settlementBusinessType_dictText || '--',
    },
    {
      label: '调整状态',
      value: businessData.value.adjustmentStatus_dictText || '--',
    },
    {
      label: '装货地',
      value: businessData.value.loadLocation || '--',
    },
    {
      label: '卸货地',
      value: businessData.value.unloadLocation || '--',
    },
    {
      label: '业务时间',
      value: businessData.value.businessTime || '--',
      type: 'datetime',
    },
    {
      label: '备注',
      value: businessData.value.remark || '--',
      forceMultiline: true,
    },
  ]
})

// 计算项目合同信息列表
const projectContractInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '项目名称',
      value: businessData.value.projectName || '--',
    },
    {
      label: '合同名称',
      value: businessData.value.contractName || '--',
    },
    {
      label: '运单号',
      value: businessData.value.waybillNo || '--',
    },
    {
      label: '车牌号',
      value: businessData.value.licensePlate || '--',
    },
    {
      label: '最大载重量',
      value: businessData.value.weightMax ? `${businessData.value.weightMax}吨` : '--',
    },
    {
      label: '是否已登记',
      value: businessData.value.isRegistered === 1 ? '是' : (businessData.value.isRegistered === 0 ? '否' : '--'),
    },
  ]
})

// 计算参与方信息列表
const partyInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '付款方',
      value: businessData.value.payerName || '--',
    },
    {
      label: '业主结算实体',
      value: businessData.value.ownerSettlementEntityName || '--',
    },
    {
      label: '系统结算实体',
      value: businessData.value.systemSettlementEntityName || '--',
    },
    {
      label: '承运商结算实体',
      value: businessData.value.carrierSettlementEntityName || '--',
    },
  ]
})

// 计算开票信息列表
const invoiceInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '是否开票',
      value: getInvoiceStatusText(businessData.value.isInvoice),
    },
    {
      label: '开票金额',
      value: businessData.value.invoiceAmount || 0,
      type: 'currency',
    },
    {
      label: '总开票金额',
      value: businessData.value.totalInvoiceAmount || '--',
      type: 'currency',
    },
  ]
})

// 计算实际收付信息列表
const actualPaymentInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '客户结算实体',
      value: businessData.value.ownerSettlementEntityName || '--',
    },
    {
      label: '支付类型',
      value: businessData.value.paymentMethod_dictText || '--',
    },
    {
      label: '承运商结算实体',
      value: businessData.value.carrierSettlementEntityName || '--',
    },
    {
      label: '系统结算实体',
      value: businessData.value.systemSettlementEntityName || '--',
    },
    {
      label: '业务时间',
      value: businessData.value.businessTime || '--',
      type: 'datetime',
    },
    {
      label: '退款金额',
      value: businessData.value.refundAmount || 0,
      type: 'currency',
    },
  ]
})

// 计算操作信息列表
const operationInfo = computed<InfoItem[]>(() => {
  if (!businessData.value)
    return []

  return [
    {
      label: '创建人',
      value: businessData.value.createName || '--',
    },
    {
      label: '创建时间',
      value: businessData.value.createTime || '--',
      type: 'datetime',
    },
    {
      label: '更新人',
      value: businessData.value.updateName || '--',
    },
    {
      label: '更新时间',
      value: businessData.value.updateTime || '--',
      type: 'datetime',
    },
  ]
})

// 计算流程信息列表
const processInfo = computed<InfoItem[]>(() => {
  if (!currentProcess.value)
    return []

  return [
    {
      label: '流程实例ID',
      value: currentProcess.value.id || '--',
    },
    {
      label: '流程状态',
      value: currentProcess.value.status || '--',
    },
  ]
})

// 获取业务详情数据
async function getBusinessData() {
  try {
    if (idValue.value) {
      await getProcessInstance(idValue.value)
      // 获取当前用户待审批任务ID
      const taskId = await getCurrentUserPendingTaskId(idValue.value)
      if (taskId) {
        flowIdValue.value = taskId
      }
      if (currentProcess.value) {
        // 这里应该调用实际的API接口获取账单结算详情
        const res = await getSysSettlementDetails(currentProcess.value.businessKey)
        businessData.value = res.data || null
      }
    }
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
  }
}

// 页面加载时获取数据
onLoad(async (e: any) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  if (e.id) {
    idValue.value = e.id
    // getBusinessData()
  }
})

// 页面显示时重新获取数据
onShow(async () => {
  if (idValue.value) {
    await getBusinessData()
  }
})
// 下拉刷新
onPullDownRefresh(async () => {
  await getBusinessData()
  uni.stopPullDownRefresh()
})
const tabValue = ref(0)
</script>

<template>
  <view class="container bg-slate-50">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      加载中...
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMessage" class="error-container">
      <text>{{ errorMessage }}</text>
      <button class="retry-btn" @click="getBusinessData">
        重新加载
      </button>
    </view>

    <!-- 使用DetailCard组件展示详情信息 -->
    <template v-else-if="businessData">
      <wd-tabs v-model="tabValue" swipeable animated sticky :offset-top="0">
        <wd-tab title="基本信息" custom-class="bg-[#f9fafb]" class="px-4 py-2.5">
          <!-- 基本信息 -->
          <DetailCard title="基本信息" :info-list="basicInfo" />

          <!-- 业务信息 -->
          <DetailCard title="业务信息" :info-list="businessInfo" />

          <!-- 参与方信息 -->
          <DetailCard title="参与方信息" :info-list="partyInfo" />

          <!-- 实际收付信息 -->
          <DetailCard title="实际收付信息" :info-list="actualPaymentInfo" />

          <!-- 操作信息 -->
          <DetailCard title="操作信息" :info-list="operationInfo" />

          <!-- 流程信息 -->
          <DetailCard title="流程信息" :info-list="processInfo" />
        </wd-tab>
        <wd-tab title="其他信息" custom-class="bg-[#f9fafb]" class="px-4 py-2.5">
          <!-- 项目合同信息 -->
          <DetailCard title="项目合同信息" :info-list="projectContractInfo" />
          <!-- 开票信息 -->
          <DetailCard title="开票信息" :info-list="invoiceInfo" />
        </wd-tab>
      </wd-tabs>
    </template>
  </view>

  <!-- 审批操作栏 -->
  <view class="approval-bar">
    <ApprovalActionBar
      v-if="flowIdValue && currentProcess?.status === 1"
      :process-id="flowIdValue"
    />
  </view>
</template>

<style scoped>
.container {
  padding-bottom: 20px;
}

.content {
  padding: 20rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.error-container {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 24px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}
</style>
